/**
 * 申请帐号控制器
 */
angular
.module('myApp')
.controller('applyController', function($scope, $location, applyManager) {
  
  $scope.$watch('isSubmitted', function() {
    $scope.isSubmitted
      ? $.showLoading('提交中...')
      : $.hideLoading();
  });

  var getFirstError = function(errors) {
    for(var key in errors) break;
    return errors[key];
  }

  $scope.processSubmit = function() {

    $scope.isSubmitted  = true;
    $scope.errorMessage = false;

    applyManager.createPost($scope.name, $scope.mobile, $scope.location)
      .then(function(data) {
        $location.path('/apply/success');
      }, function(data) {
        $scope.errorMessage = angular.isDefined(data.errors)
          ? getFirstError(data.errors)
          : data.msg;
      })
      .finally(function() {
        $scope.isSubmitted = false;
      });
  }
});
